package com.itheima.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.Comments;
import com.itheima.service.impl.CommentsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
public class WebSocketServer extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    private final CommentsServiceImpl commentsService;
    private static List<String> words = new ArrayList<>();
    @Autowired
    public WebSocketServer(CommentsServiceImpl commentsService) {
        this.commentsService = commentsService;
    }


    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (words.size() == 0){
            words=commentsService.contentsFindAll();
        }
        // 处理客户端连接
        System.out.println("客户端连接成功：" + session.getId());
        sessions.add(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收并处理客户端消息
        System.out.println("接收到消息：" + message.getPayload());
        Comments comments = objectMapper.readValue(message.getPayload(),Comments.class);
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        comments.setCreateTime(ft.format(dNow));
        comments.setSupport(0);
        comments.setIsLiked(0);
        comments.setContent(checkSensitiveWord(comments.getContent()));
        System.out.println(comments.getContent()+"-----------------");
        // 保存评论
        commentsService.contentsAdd(comments);
        // 查询最新评论
        Comments comments1 = commentsService.contentsFindNew(comments);
        // 是否刷新
        comments1.setIsRefresh(comments1.getUserId());
        // 转换成json字符串
        String dataJson = objectMapper.writeValueAsString(comments1);
        // 发送消息给客户端
        for (WebSocketSession webSocketSession : sessions) {
            if (webSocketSession.isOpen()){
                webSocketSession.sendMessage(new TextMessage(dataJson));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 处理客户端断开连接
        System.out.println("客户端断开连接：" + session.getId());
    }
    // 敏感词检测
    public static String checkSensitiveWord(String content) {
        // 敏感词替换
        // 敏感词库
        for (String word : words) {
            if (content.contains(word)) {
               content = content.replace(word, "*");
            }
        }
        return content;
    }
}